<template>
  <div>
    <a-card>
      <a-form-model :model="queryParam" v-bind="layout">
        <a-row>
          <a-col :xs="24" :sm="24" :md="18" :lg="12" :xl="8" :xxl="8">
            <a-form-model-item>
              <div class="sch">
                <a-input v-model="queryParam.query" />
                <a-button type="primary" class="search" @click="search"
                  >搜索</a-button
                >
                <a-button type="primary" @click="addUser">添加</a-button>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="18" :lg="12" :xl="8" :xxl="8"> </a-col>
        </a-row>
      </a-form-model>
      <a-table
        :row-key="(record) => record.id"
        :columns="columns"
        :data-source="userData.userList"
        :pagination="pagination"
        @change="handleTableChange"
        bordered
      >
        <span slot="action" slot-scope="text, record">
          <a-switch
            default-checked
            @change="userStatuChanged(record)"
            v-model="record.mg_state"
          />
        </span>
        <span slot="action2" slot-scope="text, record">
          <span class="edit" @click="editUser(record)">修改</span>
          <a-divider type="vertical"></a-divider>
          <span class="del" @click="delUser(record)">删除</span>
          <a-divider type="vertical"></a-divider>
          <span class="edit" @click="editUserRoles(record)">分配角色</span>
        </span>
      </a-table>
    </a-card>
    <!-- 添加用户 -->
    <a-drawer :title="title" :width="600" :visible="visible" @close="onClose">
      <a-form-model
        :model="addForm"
        ref="addUserRef"
        v-bind="layout1"
        :rules="rules"
      >
        <a-row>
          <a-col>
            <a-form-model-item label="用户名" prop="username">
              <a-input v-model="addForm.username"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col>
            <a-form-model-item label="密码" prop="password">
              <a-input v-model="addForm.password"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col>
            <a-form-model-item label="邮箱" prop="email">
              <a-input v-model="addForm.email"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col>
            <a-form-model-item label="手机号" prop="mobile">
              <a-input v-model="addForm.mobile"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          取消
        </a-button>
        <a-button type="primary" @click="addUserList"> 确定 </a-button>
      </div>
    </a-drawer>
    <!-- 修改用户信息 -->
    <a-drawer :title="title1" :width="600" :visible="visible1" @close="onClose">
      <a-form-model
        :model="editForm"
        ref="editUserRef"
        v-bind="layout1"
        :rules="rules1"
      >
        <a-row>
          <a-col>
            <a-form-model-item label="邮箱" prop="email">
              <a-input v-model="editForm.email"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col>
            <a-form-model-item label="手机号" prop="mobile">
              <a-input v-model="editForm.mobile"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          取消
        </a-button>
        <a-button type="primary" @click="editUserList"> 确定 </a-button>
      </div>
    </a-drawer>
    <!-- 分配角色 -->
    <a-drawer :title="title2" :width="600" :visible="visible2" @close="onClose">
      <a-form-model
        :model="editUserRolesForm"
        ref="editUserRolesRef"
        v-bind="layout2"
      >
        <a-row>
          <a-col>
            <a-form-model-item label="用户名" prop="username">
              <a-input v-model="editUserRolesForm.username" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <p>当前用户角色{{editUserRolesForm.username}}</p> -->
          <!-- <a-col>
            <a-form-model-item label="角色" prop="password">
              <a-input v-model="editUserRolesForm.role_id"></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col>
            <a-form-model-item label="分配角色">
              <a-select v-model="editUserRolesForm.role_id" style="width: 100%">
                <a-select-option
                  :value="item.id"
                  v-for="(item, index) in rolesList"
                  :key="index"
                >
                  {{ item.roleName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          取消
        </a-button>
        <a-button type="primary" @click="editUserRole"> 确定 </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import {
  getUserList,
  postUserList,
  putUserList,
  delUserList,
  editUserState,
  editUserRoles,
} from "@/network/user";
import { getRolesList } from "@/network/Role";
// import _ from 'lodash'
export default {
  components: {},
  data() {
    return {
      queryParam: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      addForm: {},
      //需要被分配角色的用户信息
      userInfo: {},
      rolesList: [],
      editForm: {
        email: "",
        mobile: "",
      },
      editUserRolesForm: {
        username: "",
      },
      title2: "分配角色",
      visible2: false,
      userData: {
        userList: [],
        total: 0,
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 15 },
      },
      layout1: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      layout2: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      pagination: {
        total: 0,
        current: 1,
        pageSize: 5,
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "15", "20", "25"],
      },
      title: "",
      title1: "",
      userList: [],
      visible: false,
      visible1: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, trigger: "blur" },
          { min: 6, message: "长度必须大于6位", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      rules1: {
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      columns: [
        {
          title: "序号",
          customRender: (text, record, index) => {
            return (
              this.pagination.pageSize * (this.pagination.current - 1) +
              index +
              1
            );
          },
          align: "center",
        },
        {
          title: "用户名",
          dataIndex: "username",
          align: "center",
        },
        {
          title: "邮箱",
          dataIndex: "email",
          align: "center",
        },
        {
          title: "手机号",
          dataIndex: "mobile",
          align: "center",
        },
        {
          title: "角色",
          dataIndex: "role_name",
          align: "center",
        },
        {
          title: "状态",
          dataIndex: "mg_state",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action2" },
        },
      //   {
      //   title: '仓库',
      //   dataIndex: 'warehouse',
      //   align: 'center',
      //   customRender: (text, record, index) => {
      //     return text ? text.name : ''
      //     // return text.name
      //   }
      // },
      
      //遇到格式化时间 先安装moment
      // {
      //   title: '到货时间',
      //   dataIndex: 'receiveTime',
      //   align: 'center',
      //   sorter: true,
      //   customRender: (text, record, index) => {
      //     // return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ''
      //     return moment(record.receiveTime).format('YYYY-MM-DD HH:mm:ss')
      //     // return moment(text).format('YYYY-MM-DD HH:mm:ss')
      //   }
      // },
      ],
    };
  },
  created() {
    this.getUserList();
    this.getRolesList();
  },
  methods: {
    getUserList() {
      const params = {
        query: this.queryParam.query,
        pagenum: this.pagination.current,
        pagesize: this.pagination.pageSize,
      };
      getUserList(params).then((res) => {
        if (res.meta.status !== 200) {
          this.$message.error("获取用户列表失败!");
        }
        this.$message.success("获取用户列表成功!");
        this.userData.userList = res.data.users;
        this.pagination.total = res.data.total;
      });
    },
    search() {
      this.getUserList();
    },
    handleTableChange(pagination) {
      this.pagination = pagination;
      this.getUserList();
    },
    addUser() {
      this.title = "添加用户";
      this.visible = true;
    },
    editUser(record) {
      this.editForm = _.cloneDeep(record);
      this.visible1 = true;
      this.title1 = "修改用户信息";
    },
    onClose() {
      this.visible = false;
      this.visible1 = false;
      this.visible2 = false;
    },
    addUserList() {
      this.$refs.addUserRef.validate((valid) => {
        if (!valid) return;
        const params = {
          username: this.addForm.username,
          password: this.addForm.password,
          email: this.addForm.email,
          mobile: this.addForm.mobile,
        };
        postUserList(params).then((res) => {
          this.visible = false;
          this.getUserList();
          return this.$message.success("用户添加成功了~");
        });
      });
    },
    editUserList() {
      console.log(111);
      this.$refs.editUserRef.validate((valid) => {
        if (!valid) return;
        const params = {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        };
        console.log(this.editForm.id);
        putUserList(this.editForm.id, params).then((res) => {
          this.visible1 = false;
          this.getUserList();
          return this.$message.success("用户修改成功了~");
        });
      });
    },
    delUser(record) {
      const _this = this;
      this.$confirm({
        title: "你确定要删除吗?",
        content: `${record.username}`,
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          delUserList(record.id).then(
            (res) => {
              _this.$message.success("删除成功");
              _this.getUserList();
            },
            (err) => {
              console.log(err);
            }
          );
        },
        onCancel() {
          _this.$message.info("取消删除");
        },
      });
    },
    userStatuChanged(record) {
      this.record = record;
      editUserState(this.record.id, this.record.mg_state).then((res) => {
        if (res.meta.status !== 200) {
          record.mg_state = !record.mg_state;
          return this.$message.error("更新用户状态失败!");
        }
        return this.$message.success("更新用户状态成功!");
      });
    },
    editUserRoles(record) {
      this.visible2 = true;
      this.record = record;
      //把当前用户名显示出来
      this.editUserRolesForm.username = record.username;
    },
    //角色列表
    getRolesList() {
      getRolesList().then((res) => {
        this.rolesList = res.data;
      });
    },
    //分配角色
    editUserRole() {
      editUserRoles(this.editUserRolesForm.id, {
        rid: this.editUserRolesForm.rid,
      }).then((res) => {
        this.getUserList();
        this.visible2 = false;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.sch {
  display: flex;
}
.search {
  margin-left: 10px;
  margin-right: 10px;
}
</style>